/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.faare.struts.taglib;

import org.apache.struts.taglib.TagUtils;

import java.util.Collection;
import java.util.Iterator;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;


/**
 * Library which implements a JSP tag to generate HTML code for multivalued attribute edition.
 *
 * Code generated looks like this :<br>
 * <br><pre>
 * &lt;input type="hidden" name="<i>attribute name</i>" value=""&gt;
 * &lt;select name="x<i>attribute name</i>" size="5"&gt;
 * &lt;option value="<i>attribute value</i>"&gt;<i>attribute value</i>&lt;/option&gt;
 * ...
 * &lt;/select&gt;
 * </pre>
 */
public class MultiEditTag extends TagSupport
{
    /** form name. */
    private String name;

    /** attribute name, example : description. */
    private String field;

    /** property of the form containing the values, example : user.description. */
    private String property;

    /**
     * Sets the form name.
     * @param value The name to set
     */
    public final void setName(final String value)
    {
        this.name = value;
    }

    /**
     * Sets the field name.
     * @param value The field to set
     */
    public final void setField(final String value)
    {
        this.field = value;
    }

    /**
     * Sets the name of the form property containing the values, example : user.description.
     * @param value The property to set
     */
    public final void setProperty(final String value)
    {
        this.property = value;
    }

    /**
     * @see javax.servlet.jsp.tagext.Tag#doStartTag()
     */
    @Override
	public final int doStartTag() throws JspException
    {
        StringBuffer sb = new StringBuffer();
        sb.append("<input type='hidden' name='" + field + "' value=''>");
        sb.append("<select name='x" + field + "' size='5'>");

        Collection elt = (Collection) TagUtils.getInstance().lookup(pageContext, name,
                property, null);

        if (elt != null)
        {
            Iterator iter = elt.iterator();

            while (iter.hasNext())
            {
                Object value = iter.next();
                sb.append("<option value='" + value.toString() + "'>" +
                    value.toString() + "</option>");
            }
        }

        sb.append("</select>");

        TagUtils.getInstance().write(pageContext, sb.toString());

        return SKIP_BODY;
    }
}
